package com.webermagem.controller;

import java.io.Serializable;
import java.util.Collection;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.hibernate.Session;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;


import com.webermagem.DAO.UsuarioDAO;
import com.webermagem.model.UsuarioSessao;
import com.webermagem.util.HibernateUtil;
import com.webermagem.util.SessionManager;

@ManagedBean
@SessionScoped
public class UsuarioSessaoController implements Serializable{
	
	
	private static final long serialVersionUID = -6765565374189984402L;
	private UsuarioSessao usuarioSessao;
	private UsuarioDAO usuarioDao;
	
	public UsuarioSessao getUsuarioSessao() {
		return usuarioSessao;
	}

	public void setUsuarioSessao(UsuarioSessao usuarioSessao) {
		this.usuarioSessao = usuarioSessao;
	}

	public UsuarioSessaoController() {
		usuarioSessao = new UsuarioSessao();
		usuarioDao = new UsuarioDAO();
		
		FacesContext facesContext = FacesContext.getCurrentInstance();
		
		SessionManager.setSessionAttribute(facesContext, "transacao", HibernateUtil.getSessionFactory().openSession());
		
		SecurityContext context = SecurityContextHolder.getContext();
		if (context instanceof SecurityContext){
			Authentication authentication = context.getAuthentication();
			if (authentication instanceof Authentication){
				usuarioSessao.setUsername(((User)authentication.getPrincipal()).getUsername());
				Collection<GrantedAuthority> aux = ((User)authentication.getPrincipal()).getAuthorities();
				usuarioSessao = (UsuarioSessao)usuarioDao.getByUsername((Session)SessionManager.getSessionAttribute(facesContext, "transacao"), usuarioSessao.getUsername());
				for (GrantedAuthority autorizacao : aux){
					usuarioSessao.setAuthority(autorizacao.toString());
				}
				
				SessionManager.setSessionAttribute(facesContext, "usuarioSessao", usuarioSessao);
			}
		}
	}
}
